package com.ydd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ydd.constant.JwtClaimsConstant;
import com.ydd.constant.MessageConstant;
import com.ydd.dto.ArticleLisDTO;
import com.ydd.dto.RegisterDTO;
import com.ydd.entity.*;
import com.ydd.mapper.*;
import com.ydd.properties.JwtProperties;
import com.ydd.result.PageResult;
import com.ydd.result.Result;
import com.ydd.service.BasicDataService;
import com.ydd.utils.JwtUtil;
import com.ydd.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class BasicDataServerImpl implements BasicDataService {
    @Autowired
    private YddArticleMapper yddArticleMapper;
    @Autowired
    private YddCateMapper yddCateMapper;
    @Autowired
    private YddTagMapper yddTagMapper;
    @Autowired
    private YddLinkMapper yddLinkMapper;
    @Autowired
    private YddAdvimgMapper yddAdvimgMapper;
    @Autowired
    private YddUserMapper yddUserMapper;
    @Autowired
    private JwtProperties jwtProperties;


    /**
     * 热门置顶文章数据
     *
     * @param page  limit
     * @param limit
     * @return
     */
    @Override
    public TopNewArticleVO topNewArticle(String page, String limit) {

        //接口描述
        String desc = "热门文章数据";
        //24小时最新文章数量
        long time24 = Long.valueOf(System.currentTimeMillis()) - 86400000;
        Integer new7ArticleCount = yddArticleMapper.countBy24Hours(time24);

        //一周文章最新数量
        long time24_7 = Long.valueOf(System.currentTimeMillis()) - 86400000 * 7;
        Integer new24ArticleCount = yddArticleMapper.countBy24Hours(time24_7);

        //获取最新的文章
        Page<YddArticle> articlePage = new Page<>(Long.valueOf(page), Long.valueOf(limit));
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("create_date");

        Page page1 = yddArticleMapper.selectPage(articlePage, queryWrapper);

        //获取文章数据
        List<YddArticle> records = page1.getRecords();
        List<TopNewArticleDetailVO> details = new ArrayList<>();
        for (YddArticle record : records) {
            TopNewArticleDetailVO topNewArticleDetailVO = new TopNewArticleDetailVO();
            //赋值给前端需要的vo对象
            BeanUtils.copyProperties(record, topNewArticleDetailVO);
            details.add(topNewArticleDetailVO);
        }

        //封装带统一分页结果
        PageResult pageResult = PageResult.builder()
                .count(page1.getTotal())
                .pageSize(page1.getSize())
                .currentPage(page1.getCurrent())
                .totalPages(page1.getPages())
                .data(records)
                .build();

        //返回前端需要的vo对象
        return TopNewArticleVO.builder()
                .numDay(new7ArticleCount)
                .numWeek(new24ArticleCount)
                .desc(desc)
                .list(pageResult)
                .build();
    }

    /**
     * 文章列表数据
     *
     * @param articleLisDTO
     * @return
     */
    @Override
    public Map ArticleLis(ArticleLisDTO articleLisDTO) {
        //创建分页助手
        Page<YddArticle> page = new Page<>(Integer.valueOf(articleLisDTO.getPage()),
                Integer.valueOf(articleLisDTO.getLimit()));

        LambdaQueryWrapper<YddArticle> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YddArticle::getCateid, articleLisDTO.getCateid());

        Page<YddArticle> list = yddArticleMapper.selectPage(page, wrapper);

        PageResult build = PageResult.builder()
                .count(list.getTotal())
                .totalPages(list.getPages())
                .pageSize(list.getSize())
                .currentPage(list.getCurrent())
                .data(list.getRecords())
                .build();

        Map map = new HashMap<>();
        map.put("list", build);
        return map;
    }

    /**
     * 首页和全局数据
     *
     * @return
     */
    @Override
    public FrontGlobleConfigVO globleConfig() {

        //获取所有分类
        List<YddCate> allCate = yddCateMapper.selectList(null);

        //获取所有标签
        List<YddTag> allTag = yddTagMapper.selectList(null);
        //获取所有链接
        List<YddLink> allLink = yddLinkMapper.selectList(null);

        //首页轮播图   15
        List<YddAdvImg> banner = yddAdvimgMapper.selectBypos(15);
        //侧边   13 14
        List<YddAdvImg> side1 = yddAdvimgMapper.selectBypos(14);
        List<YddAdvImg> side2 = yddAdvimgMapper.selectBypos(13);
        List<YddAdvImg> side = new ArrayList<>();
        side.addAll(side1);
        side.addAll(side2);
        //底部   12
        List<YddAdvImg> showbanner = yddAdvimgMapper.selectBypos(12);

        return FrontGlobleConfigVO.builder()
                .allCate(allCate)
                .allTag(allTag)
                .allLink(allLink)
                .banner(banner)
                .sideBanner(side)
                .showBanner(showbanner)
                .build();

    }


    /**
     * 推荐文章
     *
     * @return
     */
    @Override
    public RecommendArticleVO recommend() {

        RecommendArticleVO build = RecommendArticleVO.builder().desc("推荐的文章").build();
        List<RecommendArticleDetailVO> list = new ArrayList<>();
        //搜索itop 的文章

        List<YddArticle> yddArticles = yddArticleMapper.selectByIstop(1);

        for (YddArticle yddArticle : yddArticles) {
            if (null != yddArticle) {
                RecommendArticleDetailVO recommendArticleDetailVO = new RecommendArticleDetailVO();
                BeanUtils.copyProperties(yddArticle, recommendArticleDetailVO);
                list.add(recommendArticleDetailVO);
            }
        }
        //添加返回对象
        build.setList(list);
        return build;
    }


    /**
     * 用户注册
     *
     * @param registerDTO@return
     */
    @Override
    public RegisterVO register(RegisterDTO registerDTO) {
        //判断密码账号
        if (registerDTO.getMobile() == null || registerDTO.getMobile() == null) {
            Result.error(MessageConstant.ACCOUNT_NOT_NULL);
        }
        //添加数据
        YddUser yddUser = new YddUser();
        yddUser.setUsername(registerDTO.getMobile());
        yddUser.setPassword(registerDTO.getPassword());
        yddUser.setMobile(registerDTO.getMobile());
        //添加账号
        yddUserMapper.insert(yddUser);
        //填充对象 token
        //加载载荷
        /*Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.YDD_USER_ID, userId);
        //生成令牌
        String token = JwtUtil.createJWT(
                jwtProperties.getFrontSecretKey()
                , jwtProperties.getBackTtl(),
                claims);*/

        return null;
    }

    /**
     * 最新文章
     *
     * @return
     */
    @Override
    public ArticlessVo hot() {
        //创建条件构造器
        LambdaQueryWrapper<YddArticle> wrapper = new LambdaQueryWrapper<>();
        //添加排序条件,根据收藏数量进行排序
        wrapper.orderByDesc(YddArticle::getLovenum);
        //文章状态
        wrapper.ne(YddArticle::getStatus, 3);
        ArrayList<RAticlesVo> list = new ArrayList<>();
        //进行条件查询
        List<YddArticle> yddArticles = yddArticleMapper.selectList(wrapper);
        //循环获取六条展示数据
        for (int i = 0; i < (Math.min(yddArticles.size(), 6)); i++) {
            //根据文章分类id查询所归属的分类标签数据
            YddCate yddCate = yddCateMapper.selectById(yddArticles.get(i).getCateid());
            RAticlesVo rAticlesVo = new RAticlesVo();
            BeanUtils.copyProperties(yddArticles.get(i), rAticlesVo);
            //再获取分类名称
            rAticlesVo.setCatename(yddCate.getCatename());
            list.add(rAticlesVo);
        }
        //将数据封装到vo
        ArticlessVo rArticlessVo = new ArticlessVo();
        rArticlessVo.setList(list);

        return rArticlessVo;

    }


    /**
     * 文章详情数据
     *
     * @param id
     * @return
     */
    @Override
    public ArticleDetailsDataVo show(Integer id) {
        YddArticle yddArticle = yddArticleMapper.selectById(id);
        //更新文章点击数
        yddArticle.setClick(yddArticle.getClick() + 1);
        yddArticleMapper.updateById(yddArticle);
        YddCate yddCate = yddCateMapper.selectById(yddArticle.getCateid());
        String catename = yddCate.getCatename();

        RAticlesVo rAticlesVo = new RAticlesVo();
        BeanUtils.copyProperties(yddArticle, rAticlesVo);
        rAticlesVo.setCatename(catename);

        //把文章详情数据set到info
        ArticleDetailsDataVo articleDetailsDataVo = new ArticleDetailsDataVo();
        articleDetailsDataVo.setInfo(rAticlesVo);

        //获取上一篇id数据
        YddArticle yddArticle1 = yddArticleMapper.selectById(yddArticle.getId() - 1);
        if (ObjectUtils.isEmpty(yddArticle1)) {
            ArrayList<String> list = new ArrayList<>();
            articleDetailsDataVo.setPrev(list);
        } else {
            ArrayList<YddArticle> yddArticles = new ArrayList<>();
            yddArticles.add(yddArticle1);
            articleDetailsDataVo.setPrev(yddArticles);
        }

        //获取下一篇id数据
        YddArticle yddArticle2 = yddArticleMapper.selectById(yddArticle.getId() + 1);
        if (ObjectUtils.isEmpty(yddArticle2)) {
            articleDetailsDataVo.setNext(null);
        } else {
            ArrayList<YddArticle> yddArticles2 = new ArrayList<>();
            yddArticles2.add(yddArticle2);
            articleDetailsDataVo.setNext(yddArticles2);

            //推荐文章数据
            LambdaQueryWrapper<YddArticle> wrapper1 = new LambdaQueryWrapper<>();
            //添加排序条件,是否是推荐文章
            wrapper1.eq(YddArticle::getIshot, 1);
            List<YddArticle> yddArticles = yddArticleMapper.selectList(wrapper1);
            ArrayList<YddArticle> list = new ArrayList<>();
            for (YddArticle article : yddArticles) {
                if (list.size() < 8) {
                    list.add(article);
                }
            }
            articleDetailsDataVo.setRecommend(list);

        }
        return articleDetailsDataVo;
    }
}